#include <highgui.h>
#include <cv.h>
#include <assert.h>

/*
 * Morphological operations OPEN and CLOSE
 */
void morphologicalOperations(IplImage *frame)
{
	int k=15; // higher value gives better results ( should be odd )
	cvMorphologyEx(frame, frame, NULL,
			cvCreateStructuringElementEx(k,k,1,1,CV_SHAPE_RECT, NULL), CV_MOP_OPEN, 1);
	cvMorphologyEx(frame, frame, NULL,
			cvCreateStructuringElementEx(k,k,1,1,CV_SHAPE_RECT, NULL), CV_MOP_CLOSE, 1);

}

int main(int argc, char *argv[])
{
	cvNamedWindow("Edged", CV_WINDOW_AUTOSIZE);
	cvNamedWindow("Raw", CV_WINDOW_AUTOSIZE);

	CvCapture *cam =   cvCreateCameraCapture(1);
	assert(cam);
	CvSize dim = cvSize((int) cvGetCaptureProperty(cam, CV_CAP_PROP_FRAME_WIDTH),
						(int) cvGetCaptureProperty(cam, CV_CAP_PROP_FRAME_HEIGHT));
	IplImage *gray = cvCreateImage(dim, IPL_DEPTH_8U, 1);
	IplImage *src = cvCloneImage(gray);
	IplImage *dst=cvCreateImage(dim, IPL_DEPTH_8U, 1),*frame=cvCreateImage(dim, IPL_DEPTH_8U, 3);
	int delay = 33;

	while(true){
		frame = cvQueryFrame(cam);
		char c = cvWaitKey(delay); // get a delay of <delay> miliseconds
		if(c == 'q') break;

		cvCvtColor(frame,src , CV_BGR2GRAY); // convert to intensity image
		morphologicalOperations(src);
//		cvSobel(src, dst, 1,1,3); // edge detection

//		cvSmooth(src, dst,CV_GAUSSIAN,3,3);
		cvCanny(src, dst, 10, 50, 3);

		cvShowImage("Raw", src);
		cvShowImage("Edged", dst);
	}

	cvReleaseCapture(&cam);
	cvReleaseImage(&src);
	cvReleaseImage(&dst);
	cvDestroyWindow("Raw");
	cvDestroyWindow("Edged");
	return 0;
}
